<template>
  <view class="cart-container container uni-pa-4">
    <view class="uni-mt-4  fs-4">购物车</view>

    <!-- 购物车为空时显示 -->
    <view v-if="!cartStore.itemCount" class="empty-cart text-center uni-py-5">
      <text class="bi bi-cart-x"></text>
      <view class="uni-my-6">购物车是空的</view>
      <view @click="goToShop" class="uni-my-7">
        <button type="warn" >去购物</button>
      </view>
    </view>

    <!-- 购物车列表 -->
    <view v-else>
      <view class="cart-items">
        <uni-card
          v-for="(item, index) in cartStore.cartItems"
          :key="index"
          class="uni-py-3 animate__animated animate__fadeIn"
        >
          <view>
            <view class="">
              <view class="d-flex cart-item-row"> 
                <view class="cart-item-image">
                  <image
                    :src="url('sp', item.id-1, 'png')"
                    :alt="item.title"
                    mode="aspectFill"
                    class="product-image"
                  ></image>
                </view>
                <view class="cart-item-details">
                  <view class="cart-item-title">{{ item.title }}</view>
                  <view class="cart-item-price text-danger">
                    ¥ {{ item.price.toFixed(2) }}
                  </view>
                </view>
              </view>
              <view class="d-flex cart-item-actions justify-content-between align-items-center">
                <view class="quantity-label">数量：</view>
                <view class="quantity-box">
                  <uni-number-box
                    v-model="item.quantity"
                    :min="1"
                    :max="99"
                    @change="(value) => updateQuantity(index, value)"
                  />
                </view>
                <view class="delete-btn">
                  <button @click="removeItem(index)" type="warn" size="mini">
                    <text class="bi bi-trash"></text> 删除
                  </button>
                </view>
              </view>
            </view>
          </view>
        </uni-card>
      </view>

      <!-- 结算区域 -->
      <uni-card class="checkout-view card uni-mt-4">
        <view>
          <view class="d-flex justify-content-between align-items-center">
            <view>
              总计:
              <text class="fs-3 text-danger mb-0"
                >¥ {{ cartStore.totalAmount.toFixed(2) }}</text
              >
            </view>
            <view>
              <button type="warn" size="default" @click="goToCheckout">
                去结算
              </button></view
            >
          </view>
        </view>
      </uni-card>
    </view>

    <!-- 地址选择弹窗 -->
    <uni-popup ref="addressPopup" type="center">
      <view class="popup-content">
        <view class="popup-title">选择收货地址</view>
        <view class="address-list">
          <view v-if="!userStore.userInfo.addresses || userStore.userInfo.addresses.length === 0" class="text-center uni-py-3">
            <view class="text-muted">暂无收货地址</view>
            <button type="warn" @click="showAddAddressDialog">添加地址</button>
          </view>
          <view v-else class="address-items">
            <view
              v-for="(address, index) in userStore.userInfo.addresses"
              :key="address.id"
              class="address-item uni-pa-3 border rounded uni-py-3"
            >
              <view class="d-flex justify-content-between">
                <view>
                  <view class="fs-5"
                    >{{ address.name }} {{ address.phone }}</view
                  >
                  <view
                    >{{ address.province }}{{ address.city
                    }}{{ address.district }}{{ address.detail }}</view
                  >
                </view>
                <view>
                  <button
                    type="default"
                    size="mini"
                    @click="editAddress(address)"
                  >
                    编辑
                  </button>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </uni-popup>

    <!-- 添加/编辑地址弹窗 -->
    <uni-popup ref="addressFormPopup" type="center">
      <view class="popup-content">
        <view class="popup-title">{{
          editingAddressIndex === -1 ? "添加地址" : "编辑地址"
        }}</view>
        <uni-forms
          ref="addressForm"
          :modelValue="addressForm"
          :rules="addressRules"
        >
          <uni-forms-item label="收货人" name="name">
            <uni-easyinput
              v-model="addressForm.name"
              placeholder="请输入收货人姓名"
            />
          </uni-forms-item>

          <uni-forms-item label="手机号码" name="phone">
            <uni-easyinput
              v-model="addressForm.phone"
              placeholder="请输入手机号码"
            />
          </uni-forms-item>

          <uni-forms-item label="所在地区" name="region">
            <uni-data-picker
              v-model="addressForm.region"
              :localdata="cityData"
              placeholder="请选择所在地区"
            />
          </uni-forms-item>

          <uni-forms-item label="详细地址" name="detail">
            <uni-easyinput
              v-model="addressForm.detail"
              type="textarea"
              placeholder="请输入详细地址"
            />
          </uni-forms-item>

          <view class="text-end mt-4">
            <button @click="closeAddressForm">取消</button>
            <button type="warn" @click="submitAddressForm" class="ms-2">
              保存
            </button>
          </view>
        </uni-forms>
      </view>
    </uni-popup>
  </view>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { useCartStore } from "@/stores/cartStore";
import { useUserStore } from "@/stores/userStore";

const cartStore = useCartStore();
const userStore = useUserStore();
const url = $url;

// 地址管理相关
const addressPopup = ref(null);
const addressFormPopup = ref(null);
const editingAddressIndex = ref(-1);
const addressForm = ref({
  name: "",
  phone: "",
  region: [],
  detail: "",
});

// 城市数据
const cityData = [
  {
    text: "江西省",
    value: "360000",
    children: [
      {
        text: "南昌市",
        value: "360100",
      },
      {
        text: "上饶市",
        value: "361100",
      },
      // ... 其他城市
    ],
  },
  // ... 其他省份
];

// 表单验证规则
const addressRules = {
  name: {
    rules: [{ required: true, errorMessage: "请输入收货人姓名" }],
  },
  phone: {
    rules: [
      { required: true, errorMessage: "请输入手机号码" },
      { pattern: /^1[3-9]\d{9}$/, errorMessage: "请输入正确的手机号码" },
    ],
  },
  region: {
    rules: [{ required: true, errorMessage: "请选择所在地区" }],
  },
  detail: {
    rules: [{ required: true, errorMessage: "请输入详细地址" }],
  },
};

// 在组件挂载时加载数据
onMounted(() => {
  cartStore.loadFromStorage();
});

// 更新商品数量
const updateQuantity = (index, value) => {
  cartStore.updateQuantity(index, value);
  cartStore.saveToStorage();
};

// 删除商品
const removeItem = (index) => {
  cartStore.removeFromCart(index);
  cartStore.saveToStorage();
  uni.showToast({
    title: "已从购物车移除",
    icon: "success",
  });
};

// 显示地址选择弹窗
const showAddressDialog = () => {
  addressPopup.value.open();
};

// 显示添加地址弹窗
const showAddAddressDialog = () => {
  editingAddressIndex.value = -1;
  addressForm.value = {
    name: "",
    phone: "",
    region: [],
    detail: "",
    isDefault: false
  };
  addressFormPopup.value.open();
};

// 编辑地址
const editAddress = (address) => {
  addressForm.value = {
    id: address.id,
    name: address.name,
    phone: address.phone,
    region: [address.province, address.city, address.district],
    detail: address.detail,
    isDefault: address.isDefault || false
  };
  addressFormPopup.value.open();
};

// 关闭地址表单
const closeAddressForm = () => {
  addressFormPopup.value.close();
};

// 提交地址表单
const submitAddressForm = () => {
  // 表单验证
  if (!addressForm.value.name) {
    return uni.showToast({
      title: '请输入收货人姓名',
      icon: 'none'
    });
  }
  
  if (!/^1\d{10}$/.test(addressForm.value.phone)) {
    return uni.showToast({
      title: '请输入正确的手机号码',
      icon: 'none'
    });
  }
  
  if (!addressForm.value.region || addressForm.value.region.length < 3) {
    return uni.showToast({
      title: '请选择所在地区',
      icon: 'none'
    });
  }
  
  if (!addressForm.value.detail) {
    return uni.showToast({
      title: '请输入详细地址',
      icon: 'none'
    });
  }
  
  // 构建地址对象
  const addressData = {
    id: addressForm.value.id,
    name: addressForm.value.name,
    phone: addressForm.value.phone,
    province: addressForm.value.region[0],
    city: addressForm.value.region[1],
    district: addressForm.value.region[2],
    detail: addressForm.value.detail,
    isDefault: addressForm.value.isDefault
  };
  
  // 保存地址
  if (addressData.id) {
    // 更新地址
    userStore.updateAddress(addressData);
    uni.showToast({
      title: '地址已更新',
      icon: 'success'
    });
  } else {
    // 添加新地址
    userStore.addAddress(addressData);
    uni.showToast({
      title: '地址已添加',
      icon: 'success'
    });
  }
  
  // 关闭弹窗
  addressFormPopup.value.close();
};

const goToShop = () => {
  uni.switchTab({
    url: "/pages/shop/index",
  });
};

// 转到结算页面
const goToCheckout = () => {
  // 检查是否有地址
  const addresses = userStore.userInfo.addresses || [];
  if (addresses.length === 0) {
    uni.showToast({
      title: '请先添加收货地址',
      icon: 'none'
    });
    showAddressDialog();
    return;
  }
  
  // 将购物车信息传递给结算页面
  uni.navigateTo({
    url: '/pages/other/cart/checkout',
    success: () => {
      console.log('跳转到结算页面成功');
    },
    fail: (err) => {
      console.error('跳转失败:', err);
      uni.showToast({
        title: '跳转失败，请重试',
        icon: 'none'
      });
    }
  });
};
</script>

<style scoped>
.cart-container {
  padding-bottom: 120rpx;
  background-color: #f5f5f5;
}

.empty-cart {
  color: #999;
  padding: 80rpx 0;
}

.empty-cart .bi {
  font-size: 120rpx;
  display: block;
  margin-bottom: 30rpx;
  color: #ccc;
}

.cart-items {
  margin-top: 30rpx;
}

.cart-item-row {
  margin-bottom: 20rpx;
}

.cart-item-image {
  width: 180rpx;
  height: 180rpx;
  margin-right: 20rpx;
  border-radius: 12rpx;
  overflow: hidden;
  background-color: #f8f8f8;
  box-shadow: 0 4rpx 8rpx rgba(0,0,0,0.05);
}

.product-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.cart-item-details {
  flex: 1;
  padding: 10rpx 0;
}

.cart-item-title {
  font-size: 32rpx;
  font-weight: bold;
  margin-bottom: 20rpx;
  line-height: 1.4;
}

.cart-item-price {
  font-size: 36rpx;
  font-weight: bold;
}

.cart-item-actions {
  margin-top: 30rpx;
  padding-top: 20rpx;
  border-top: 1px solid #eee;
}

.quantity-label {
  font-size: 28rpx;
  color: #666;
}

.quantity-box {
  flex: 1;
  display: flex;
  justify-content: center;
}

.delete-btn {
  margin-left: 20rpx;
}

.checkout-view {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  padding: 20rpx 30rpx;
  background-color: #fff;
  box-shadow: 0 -2rpx 10rpx rgba(0,0,0,0.05);
  z-index: 100;
  border-radius: 20rpx 20rpx 0 0;
}

.popup-content {
  width: 650rpx;
  padding: 40rpx;
  background-color: #fff;
  border-radius: 20rpx;
}

.popup-title {
  font-size: 36rpx;
  font-weight: bold;
  margin-bottom: 30rpx;
  text-align: center;
  border-bottom: 1px solid #eee;
  padding-bottom: 20rpx;
}

.address-list {
  max-height: 600rpx;
  overflow-y: auto;
}

.address-items {
  margin-top: 20rpx;
}

.address-item {
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.05);
  transition: all 0.3s;
}

.address-item:last-child {
  margin-bottom: 0;
}

.address-item:hover, .address-item.active {
  background-color: #f8f8f8;
  border-color: #ddd !important;
}
</style>
